package com.springboot.oauth2.intercepter;

import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.PublicKey;
import java.security.cert.CertificateFactory;
import java.util.Map;

@Component
@Slf4j
public class WebInterceptor implements HandlerInterceptor {

  @Override
  public boolean preHandle(
      HttpServletRequest request, HttpServletResponse response, Object handler) {
    // 拿到token
    String authorization = request.getHeader("Authorization");
    if (authorization == null) {
      try {
        response.getWriter().write("未授权");
      } catch (IOException e) {
        e.printStackTrace();
      }
      return false;
    }
    String token = authorization.replace("Bearer ", "");
    Claims claims = null;
    try {
      // 加载公钥
      ClassPathResource resource = new ClassPathResource("pubKey.cer");
      PublicKey publicKey =
          CertificateFactory.getInstance("X.509")
              .generateCertificate(resource.getInputStream())
              .getPublicKey();
      // 解析Jwt
      claims = Jwts.parser().setSigningKey(publicKey).parseClaimsJws(token).getBody();
    } catch (ExpiredJwtException e) {
      System.out.println(e.getMessage());
    } catch (Exception e) {
      System.out.println(e.getMessage());
    }
    Map map = JSON.parseObject(JSON.toJSONString(claims), Map.class);
    log.info("Token内容:{}", map);
    return true;
  }
}
